<template>

    <div class="row">
        <el-input v-model="searchKey" style="width: 240px" placeholder="输入关键字，回车搜索" :suffix-icon="Search" />

        <el-button v-hasPerm="['sys:employee:add']" type="primary" :icon="CirclePlus" @click="eidtDialog(null)">添加员工</el-button>

    </div>

    <el-table :data="userList" v-loading="loading">
        <el-table-column fixed label="姓名" align="center" prop="employeeName" width="100"></el-table-column>
        <el-table-column label="部门" align="center" prop="deptName" width="100"></el-table-column>
        <el-table-column label="职位" prop="jobName" align="center" widht="100"></el-table-column>
        <el-table-column label="工号" prop="employeeNo" align="center" widht="100"></el-table-column>
        <el-table-column label="手机号" align="center" prop="phone" width="160"></el-table-column>
        <el-table-column label="身份证" align="center" prop="idcard" width="100"></el-table-column>
        <el-table-column label="性别" prop="gender" align="center" width="80"></el-table-column>
        <el-table-column label="生日" align="center" prop="birth" width="160"></el-table-column>
        <el-table-column label="身高" prop="height" align="center" width="80"></el-table-column>
        <el-table-column label="体重" prop="weight" align="center" width="80"></el-table-column>
        <el-table-column fixed="right" align="right" label="操作" width="160">
            <template #default="scope">
                <el-button type="warning" link size="small" v-hasPerm="['sys:employee:edit']"
                    @click="eidtDialog(scope.row)">编辑</el-button>
                <el-button type="danger" link size="small" v-hasPerm="['sys:employee:delete']"
                    @click="deleteUser(scope.row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-drawer v-model="dialog" title="用户编辑" direction="rtl" :before-close="handleClose">
        <el-form ref="userFormRef" :model="userForm" :rules="rules" :inline="true" label-width="auto"
            label-position="right" require-asterisk-position="right">
            <el-form-item label="员工姓名">
                <el-input v-model="userForm.employeeName"></el-input>
            </el-form-item>
            <el-form-item label="用户密码">
                <el-input v-model="userForm.password"></el-input>
            </el-form-item>
            <el-form-item label="所属部门">
                <el-tree-select v-model="userForm.deptId" placeholder="选择部门" :data="deptOptions" filterable
                check-strictly :render-after-expand="false" style="width:200px"/>
            </el-form-item>
            <el-form-item label="职位">
                <el-select v-model="userForm.jobId" placeholder="选择职位" style="width: 200px">
                    <el-option v-for="item in jobs" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="手机号码">
                <el-input v-model="userForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="身份证">
                <el-input v-model="userForm.idcard"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
                <el-input v-model="userForm.email"></el-input>
            </el-form-item>
            <el-form-item label="生日">
                <el-date-picker v-model="userForm.birth" type="date" editable placeholder="选择生日"
                    value-format="YYYY-MM-DD" @change="onBirthChange"style="width:200px"/>
            </el-form-item>
            <el-form-item label="身高" width="80px">
                <el-input v-model="userForm.height"></el-input>
            </el-form-item>
            <el-form-item label="体重" width="80px">
                <el-input v-model="userForm.weight"></el-input>
            </el-form-item>
            <el-form-item label="性别">
                <el-radio-group v-model="userForm.sex">
                    <el-radio :value="sex.id" size="large" v-for="sex in sexItems" :key="sex.id">{{sex.name}}</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-button @click="submit" style="width: 100%;" type="primary" round>确定</el-button>
        </el-form>
    </el-drawer>
</template>

<script setup>

import DeptApi from '@/api/dept';
import DictApi from '@/api/dict';
import EmployeeApi from '@/api/employee';

import { CirclePlus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue';

let searchKey = ref("")
let loading = ref(true)
let userList = ref()
let dialog = ref(false)
let userFormRef = ref()
const rules = reactive({
    employeeName: [{ required: true, message: "员工姓名不能为空", trigger: "blur" }],
    jobId: [{ required: true, message: "请选择职位", trigger: "blur" }],
    deptId: [{ required: true, message: "请选择部门", trigger: "blur" }]
});

let initUser = {
    id: 0,
    userId: 0,
    password: "",
    employeeName: "",
    employeeNo: "",
    nickName: "",
    jobName: "",
    jobId: 0,
    sex: 0,
    gender: "",
    deptId: 0,
    deptName: "",
    deptCode: "",
    phone: "",
    birth: "",
    height: "",
    weight: "",
    email: "",
    avatar: "",
    address: "",
    region: ""
}

let userForm = ref(initUser)
let deptOptions = ref([])
let jobs = ref([])
let sexItems = ref([])
let deptList = []
onMounted(() => {
    loadUers()
    EmployeeApi.getJobs().then(list=>{
        jobs.value = list.map(i => {
            return { label: i.name, value: i.id }
        })
    })
    DeptApi.listAll().then(list => {
        deptOptions.value = mapDeptList(list)
        deptList = list
    })
    DictApi.getDictByCode("gender").then(list=>{
        sexItems.value = list
    })
})

function loadUers() {
    EmployeeApi.getList(1, 50).then(userDto => {
        userList.value = userDto.list
        loading.value = false
    })
}

async function eidtDialog(user) {
    dialog.value = true
    if (user) {
        userForm.value = user
        userForm.value.password = ""
        console.log("sexs", sexItems.value)
        console.log("userForm", userForm.value)
    }
}

function submit() {
    userFormRef.value.validate(isValided => {
        if (isValided) {
            EmployeeApi.saveOrUpdate(userForm.value).then(res => {
                if(res){
                    dialog.value = false
                    userForm.value = initUser
                    loadUers()
                    ElMessage({
                        message: '添加或更新员工成功!',
                        type: 'success',
                    })
                } 
            })
        }
    })
}

function deleteUser(userId) {
    ElMessageBox.confirm(
        '是否真的删除此员工?',
        '警告',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        UserApi.delUser(userId).then(res => {
            if (res) {
                ElMessage({
                    type: 'success',
                    message: '删除成功！',
                })
            }

            loadUers()
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: 'Delete canceled',
        })
    })
}

function handleClose() {
    dialog.value = false
    userForm.value = initUser
}

function mapDeptList(list) {
    return list.map(i => {
        let item = { value: i.id, label: i.name }
        if (i.children && i.children.length > 0) {
            item.children = mapDeptList(i.children)
        }
        return item
    })
}
</script>

<style lang="css">
.row {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
}
</style>